package nacos

import (
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/clients/naming_client"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"saleforce/sf-backend-gateway/config"
	utils "saleforce/sf-common/utils"
	"time"
)

func NewNamingClient() naming_client.INamingClient {
	sc := []constant.ServerConfig{
		*constant.NewServerConfig(config.NacosConf.IP, config.NacosConf.Port),
	}
	cc := *constant.NewClientConfig(
		constant.WithNamespaceId(config.NacosConf.Namespace),
		constant.WithNotLoadCacheAtStart(true),
	)
	client, err := clients.NewNamingClient(vo.NacosClientParam{
		ClientConfig:  &cc,
		ServerConfigs: sc,
	})
	if err != nil {
		panic(fmt.Sprintf("初始化Nacos客户端失败: %v", err))
	}
	return client
}

func NewRegisterParam() vo.RegisterInstanceParam {
	ip, err := utils.GetLocalIP()
	if err != nil {
		panic("ip获取异常")
	}
	return vo.RegisterInstanceParam{
		Ip:          ip,
		Port:        config.ServerConf.Port,
		ServiceName: config.NacosConf.ServiceName,
		Weight:      config.NacosConf.Weight,
		Enable:      true,
		Healthy:     true,
		Ephemeral:   true,
		ClusterName: "DEFAULT",
		GroupName:   config.NacosConf.Group,
		Metadata:    map[string]string{"version": "1.0.0"},
	}
}

func RegisterWithRetry(client naming_client.INamingClient, param vo.RegisterInstanceParam, maxRetries int, retryInterval time.Duration) error {
	var err error
	for i := 0; i < maxRetries; i++ {
		_, err = client.RegisterInstance(param)
		if err == nil {
			fmt.Printf("✅ 成功注册到 Nacos\n")
			return nil
		}
		fmt.Printf("❌ 注册失败，第 %d 次，err: %v\n", i+1, err)
		time.Sleep(retryInterval)
	}
	return err
}
